﻿/****************************************************************************************************
 * @authors: Paweł Lew-Kiedrowski & Mateusz Łajming
 * based on Google Street View viewer for the Oculus Rift by troffmo5 http://github.com/troffmo5
 *
 * VIRTUAL WALK Initializer
 ****************************************************************************************************/

function initialize()
{
    initWebGL();
    initGoogleMap();
    initPano();
    initControls();
    initWebSocket();

    $("#tabs").tabs();
}

function initWebGL() {
    // create scene
    scene = new THREE.Scene();

    // Create camera
    camera = new THREE.PerspectiveCamera(60, WIDTH / HEIGHT, 0.1, 1000);
    camera.target = new THREE.Vector3(1, 0, 0);
    camera.useQuaternion = true;
    scene.add(camera);

    // Add projection sphere
    projSphere = new THREE.Mesh(new THREE.SphereGeometry(500, 512, 256), new THREE.MeshBasicMaterial({ map: THREE.ImageUtils.loadTexture('placeholder.png'), side: THREE.DoubleSide }));
    projSphere.geometry.dynamic = true;
    projSphere.useQuaternion = true;
    scene.add(projSphere);

    // Create render
    try {
        renderer = new THREE.WebGLRenderer();
    }
    catch (e) {
        alert('This application needs WebGL enabled!');
        return false;
    }

    renderer.autoClearColor = false;
    renderer.setSize(WIDTH, HEIGHT);

    // Set the window resolution of the rift in case of not native
    OculusRift.hResolution = WIDTH, OculusRift.vResolution = HEIGHT,

    effect = new THREE.OculusRiftEffect(renderer, { HMD: OculusRift, worldFactor: WORLD_FACTOR });
    effect.setSize(WIDTH, HEIGHT);

    var viewer = $('#viewer');
    viewer.append(renderer.domElement);
}

function initPano() {
    panoLoader = new GSVPANO.PanoLoader();
    panoLoader.setZoom(QUALITY);

    panoLoader.onPanoramaLoad = function () {
        var a = THREE.Math.degToRad(90-panoLoader.heading);
        projSphere.quaternion.setFromEuler(new THREE.Vector3(0, a, 0), 'YZX');

        projSphere.material.wireframe = false;
        projSphere.material.map.needsUpdate = true;
        projSphere.material.map = new THREE.Texture(this.canvas);
        projSphere.material.map.needsUpdate = true;
        centerHeading = panoLoader.heading;

        notifyOptions.className = 'success';
        $("#leftInfo").notify("Wczytano panoramę", notifyOptions);
        $("#rightInfo").notify("Wczytano panoramę", notifyOptions);
        marker.setMap(null);
        marker = new google.maps.Marker({ position: this.location.latLng, map: googleMap });
        marker.setMap(googleMap);
    };

    panoLoader.onNoPanoramaData = function (status) {
        notifyOptions.className = 'error';
        $("#leftInfo").notify("Nie znaleziono panoramy :(", notifyOptions);
        $("#rightInfo").notify("Nie znaleziono panoramy :(", notifyOptions);
    };
}

function initGoogleMap() {
    $('.mapprogress').progressbar({ value: false });

    currentLocation = new google.maps.LatLng(DEFAULT_LOCATION.lat, DEFAULT_LOCATION.lng);

    googleMap = new google.maps.Map($('#map')[0], {
        zoom: 14,
        center: currentLocation,
        mapTypeId: google.maps.MapTypeId.HYBRID,
        streetViewControl: false
    });
    google.maps.event.addListener(googleMap, 'click', function (event) {
        notifyOptions.className = 'info';
        $("#leftInfo").notify("Wczytywanie panoramy", "info");
        $("#rightInfo").notify("Wczytywanie panoramy", "info");
        panoLoader.load(event.latLng);
    });

    marker = new google.maps.Marker({ position: currentLocation, map: googleMap });
    marker.setMap(googleMap);
}

function initControls() {
    $(document).keydown(function (e) {
        switch (e.keyCode) {
            case 32: // Space
                moveToNextPlace();
                break;
            case 17: //ctrl
                $('#propWindow').toggle(200);
                break;
        }
    });

    // Mouse
    // ---------------------------------------
    var viewer = $('#viewer'),
        mouseButtonDown = false,
        lastClientX = 0,
        lastClientY = 0;

    viewer.mousedown(function (event) {
        mouseButtonDown = true;
        lastClientX = event.clientX;
        lastClientY = event.clientY;
    });

    viewer.mouseup(function () {
        mouseButtonDown = false;
    });

    viewer.mousemove(function (event) {
        if (mouseButtonDown) {
            BaseRotationEuler.set(
              BaseRotationEuler.x + (event.clientY - lastClientY) * MOUSE_SPEED,
              BaseRotationEuler.y + (event.clientX - lastClientX) * MOUSE_SPEED,
              0.0
            );
            lastClientX = event.clientX;
            lastClientY = event.clientY;
            //BaseRotation.setFromEuler(BaseRotationEuler, 'YZX');
        }
    });
}

function initWebSocket() {
    connection = new WebSocket(DEFAULT_WEBSOCKET_ADDRESS);
    connection.onopen = function () {
        console.log('websocket open');
    };
    connection.onerror = function (error) {
        console.log('websocket error');
    };

    connection.onmessage = function (message) {
        //var data = JSON.parse('[' + message.data + ']');
        //HMDRotation.set(data[1], data[2], data[3], data[0]);
        var data = JSON.parse('[' + message.data + ']');
        console.log(data[0], data[1], data[2]);
         BaseRotationEuler.set(
           data[1],
           data[0],
           data[2]
         );
    };

    connection.onclose = function () {
        console.log('websocket close');
        setTimeout(initWebSocket, 1000); // retry
    };
}